package com.example.administrator.schoolblog;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.example.administrator.schoolblog.Beans.BlogUser;
import com.example.administrator.schoolblog.Beans.UserContent;
import com.github.mr5.icarus.Callback;
import com.github.mr5.icarus.Icarus;
import com.github.mr5.icarus.TextViewToolbar;
import com.github.mr5.icarus.button.FontScaleButton;
import com.github.mr5.icarus.button.TextViewButton;
import com.github.mr5.icarus.entity.Html;
import com.github.mr5.icarus.entity.Options;
import com.github.mr5.icarus.popover.FontScalePopoverImpl;
import com.github.mr5.icarus.popover.HtmlPopoverImpl;
import com.github.mr5.icarus.popover.ImagePopoverImpl;
import com.github.mr5.icarus.popover.LinkPopoverImpl;
import com.google.gson.Gson;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class TucaoActivity extends BaseActivity {
    protected WebView webView;
    protected Icarus icarus;
    private MaterialEditText title_editText;
    private Html html;
    private Button submit_Button;
    private String html_content;
    private String UserId;
    private String nickname;
    private String userIconUrl;
    private String title;
    private static final int RESULT_CHOOSE_LOCATION = 1;
    private static final int RESULT_CHOOSE_PHOTO = 2;
    private String picPath;
    private BmobFile upImageFile;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.blog_tucao);
        Bmob.initialize(this,"b5d62a501dc94902d3f8672a1b5fc2ab","Bmob");
        initView();
    }
    private void initView(){
        //获取intent传递UserId;
        Intent intent = getIntent();
        UserId = intent.getStringExtra("UserId");
        //toolBar设置
        Toolbar tucao_toolbar =(Toolbar) findViewById(R.id.blog_tucao_toolbar);
        setSupportActionBar(tucao_toolbar);
        ActionBar tucao_actionBar = getSupportActionBar();
        if(tucao_actionBar!=null){
            tucao_actionBar.setDisplayHomeAsUpEnabled(true);
            //tucao_actionBar.setDisplayShowTitleEnabled(false);
        }
        tucao_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //icarus_editor设置
        webView = (WebView) findViewById(R.id.blog_tucao_editor_webView);
        TextViewToolbar textViewToolbar = new TextViewToolbar();
        Options options = new Options();
        options.setPlaceholder("请输入内容....");
        //  img: ['src', 'alt', 'width', 'height', 'data-non-image']
        // a: ['href', 'target']
        options.addAllowedAttributes("img", Arrays.asList("data-type", "data-id", "class", "src", "alt", "width", "height", "data-non-image"));
        options.addAllowedAttributes("iframe", Arrays.asList("data-type", "data-id", "class", "src", "width", "height"));
        options.addAllowedAttributes("a", Arrays.asList("data-type", "data-id", "class", "href", "target", "title"));
        icarus = new Icarus(textViewToolbar,options,webView);
        prepareToolbar(textViewToolbar, icarus);
        icarus.loadCSS("file:///android_asset/editor.css");
        icarus.loadJs("file:///android_asset/test.js");
        icarus.render();
        //吐槽标题监听
        title_editText = (MaterialEditText) findViewById(R.id.blog_tucao_label_edit_text);
        title_editText.addTextChangedListener(textWatcher);
        //提交按钮实例化
        submit_Button = (Button) findViewById(R.id.blog_tucao_submit_button);
        submit_Button.setTextColor(getResources().getColor(R.color.tucao_submit_on));
        //submit_Button.setEnabled(false);
        submit_Button.setOnClickListener(new OnClickListener());
    }
    /**
     * 吐槽标题监听函数
     */
        private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //tucao_content_change();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //tucao_content_change();
        }

        @Override
        public void afterTextChanged(Editable s) {
            //tucao_content_change();
        }
    };
    /**
     * 标题文本内容具体变化判断函数
     */
    private void tucao_content_change(){
        title = title_editText.getText().toString().trim();
        icarus.getContent(new Callback() {
            @Override
            public void run(String params) {
                Gson gson = new Gson();
                html = gson.fromJson(params,Html.class);
                html_content = html.getContent();
                //Toast.makeText(TucaoActivity.this, "content:"+html_content, Toast.LENGTH_SHORT).show();
                if(title.equals("")==false&&title!=null&&html_content.equals("")==false&&html_content!=null){
                    submit_Button.setTextColor(getResources().getColor(R.color.tucao_submit_on));
                    submit_Button.setEnabled(true);
                    //Toast.makeText(TucaoActivity.this, "标题内容都不为空,"+"标题:"+title+"内容:"+html_content, Toast.LENGTH_SHORT).show();
                }else{
                    submit_Button.setTextColor(getResources().getColor(R.color.tucao_submit_off));
                    submit_Button.setEnabled(false);
                    //Toast.makeText(TucaoActivity.this, "标题内容总有空的,"+"标题:"+title+"内容:"+html_content, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    /**
     *
     *
     * @param toolbar
     * @param icarus
     * @return
     */
    private com.github.mr5.icarus.Toolbar prepareToolbar(TextViewToolbar toolbar, Icarus icarus) {
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "Simditor.ttf");
        HashMap<String, Integer> generalButtons = new HashMap<>();
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_BOLD, R.id.button_bold);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_OL, R.id.button_list_ol);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_BLOCKQUOTE, R.id.button_blockquote);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_HR, R.id.button_hr);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_UL, R.id.button_list_ul);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_ALIGN_LEFT, R.id.button_align_left);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_ALIGN_CENTER, R.id.button_align_center);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_ALIGN_RIGHT, R.id.button_align_right);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_ITALIC, R.id.button_italic);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_INDENT, R.id.button_indent);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_OUTDENT, R.id.button_outdent);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_CODE, R.id.button_math);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_UNDERLINE, R.id.button_underline);
        generalButtons.put(com.github.mr5.icarus.button.Button.NAME_STRIKETHROUGH, R.id.button_strike_through);

        for (String name : generalButtons.keySet()) {
            TextView textView = (TextView) findViewById(generalButtons.get(name));
            if (textView == null) {
                continue;
            }
            textView.setTypeface(iconfont);
            TextViewButton button = new TextViewButton(textView, icarus);
            button.setName(name);
            toolbar.addButton(button);
        }
        TextView linkButtonTextView = (TextView) findViewById(R.id.button_link);
        linkButtonTextView.setTypeface(iconfont);
        TextViewButton linkButton = new TextViewButton(linkButtonTextView, icarus);
        linkButton.setName(com.github.mr5.icarus.button.Button.NAME_LINK);
        linkButton.setPopover(new LinkPopoverImpl(linkButtonTextView, icarus));
        toolbar.addButton(linkButton);

        TextView imageButtonTextView = (TextView) findViewById(R.id.button_image);
        imageButtonTextView.setTypeface(iconfont);
        TextViewButton imageButton = new TextViewButton(imageButtonTextView, icarus);
        imageButton.setName(com.github.mr5.icarus.button.Button.NAME_IMAGE);
        imageButton.setPopover(new ImagePopoverImpl(imageButtonTextView, icarus));
        toolbar.addButton(imageButton);

        TextView htmlButtonTextView = (TextView) findViewById(R.id.button_html5);
        htmlButtonTextView.setTypeface(iconfont);
        TextViewButton htmlButton = new TextViewButton(htmlButtonTextView, icarus);
        htmlButton.setName(com.github.mr5.icarus.button.Button.NAME_HTML);
        htmlButton.setPopover(new HtmlPopoverImpl(htmlButtonTextView, icarus));
        toolbar.addButton(htmlButton);

        TextView fontScaleTextView = (TextView) findViewById(R.id.button_font_scale);
        fontScaleTextView.setTypeface(iconfont);
        TextViewButton fontScaleButton = new FontScaleButton(fontScaleTextView, icarus);
        fontScaleButton.setPopover(new FontScalePopoverImpl(fontScaleTextView, icarus));
        toolbar.addButton(fontScaleButton);
        return toolbar;
    }
    /**
     * 按钮点击事件函数
     */
    private class OnClickListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.blog_tucao_submit_button:
                    title = title_editText.getText().toString().trim();
                    icarus.getContent(new Callback() {
                        @Override
                        public void run(String params) {
                            Gson gson = new Gson();
                            html = gson.fromJson(params,Html.class);
                            html_content = html.getContent();
                            if(title.equals("")==false&&title!=null&&html_content.equals("")==false&&html_content!=null){
                                upFengmianDialog();
                            }else{
                                Toast.makeText(TucaoActivity.this, "请填写标题和内容", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.tucao_menu,menu);
        return true;
    }
    /**
     * 添加封面Dialog函数
     */
    private void upFengmianDialog(){
        final String items[] = {"有封面发表","无封面发表"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("是否上传封面");
        builder.setIcon(R.drawable.blog_up_fenmian);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(items[which].equals("无封面发表")){
                    BmobQuery<BlogUser> userInfo = new BmobQuery<BlogUser>();
                    userInfo.getObject(UserId, new QueryListener<BlogUser>() {
                        @Override
                        public void done(BlogUser blogUser, BmobException e) {
                            if (e==null){
                                String nickname = blogUser.getNickname();
                                String userIconUrl = blogUser.getUserIconUrl();
                                UserContent userContent = new UserContent();
                                userContent.setUserId(UserId);
                                userContent.setContent(html_content);
                                userContent.setContentType("a");
                                userContent.setTitle(title);
                                userContent.setUserIconUrl(userIconUrl);
                                userContent.setUserNickname(nickname);
                                userContent.save(new SaveListener<String>() {
                                    @Override
                                    public void done(String objectId, BmobException e) {
                                        if (e==null){
                                            Toast.makeText(TucaoActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
                                            finish();
                                        }else {
                                            Toast.makeText(TucaoActivity.this, "发表失败"+e.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }else {
                                Toast.makeText(TucaoActivity.this, "获取信息失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }else {
                    MultiImageSelectorActivity.startSelect(TucaoActivity.this,
                            RESULT_CHOOSE_PHOTO, 1, MultiImageSelectorActivity.MODE_SINGLE);
                    //startActivity(new Intent(TucaoActivity.this,EditinfoActivity.class));
                }
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                //Toast.makeText(TucaoActivity.this, "确定", Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();
    }
    /**
     * 含封面上传数据函数
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_CHOOSE_PHOTO) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> mSelectPath =
                        data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);

                for (String p : mSelectPath) {
                    picPath = p;
                    //Toast.makeText(this, picPath, Toast.LENGTH_SHORT).show();
                }
                MaterialDialog.Builder submit_waitting = new MaterialDialog.Builder(this);
                submit_waitting.title("发表中")
                        .content("请等待...")
                        .progress(true,0)
                        .progressIndeterminateStyle(true);
                final MaterialDialog waitting_dialog = submit_waitting.show();
                upImageFile = new BmobFile(new File(picPath));
                upImageFile.uploadblock(new UploadFileListener() {
                    @Override
                    public void done(BmobException e) {
                        if(e==null){
                            BmobQuery<BlogUser> userInfo = new BmobQuery<BlogUser>();
                            userInfo.getObject(UserId, new QueryListener<BlogUser>() {
                                @Override
                                public void done(BlogUser blogUser, BmobException e) {
                                    if (e==null){
                                        String nickname = blogUser.getNickname();
                                        String userIconUrl = blogUser.getUserIconUrl();
                                        UserContent userContentCover = new UserContent();
                                        userContentCover.setCoverUrl(upImageFile.getFileUrl());
                                        userContentCover.setUserId(UserId);
                                        userContentCover.setContent(html_content);
                                        userContentCover.setContentType("a");
                                        userContentCover.setTitle(title);
                                        userContentCover.setUserNickname(nickname);
                                        userContentCover.setUserIconUrl(userIconUrl);
                                        userContentCover.save(new SaveListener<String>() {
                                            @Override
                                            public void done(String objectId, BmobException e) {
                                                if (e==null){
                                                    Toast.makeText(TucaoActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
                                                    waitting_dialog.dismiss();
                                                    finish();
                                                }else {
                                                    Toast.makeText(TucaoActivity.this, "发表失败"+e.getMessage(), Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        });
                                    }else {
                                        Toast.makeText(TucaoActivity.this, "获取信息失败", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    }
                });
            }
        }
    }
}
